package com.nmgydy.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class SSHFtp {
	//sftp上传文件到服务器
	public static boolean  putFile(String ip, String user, String psw ,int port, String src,String dst){
		try {
			sshSftp(ip, user, psw, port, src, dst);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	private static void sshSftp(String ip, String user, String psw ,int port, String src,String dst) throws Exception{
		Session session = null;
		Channel channel = null;
		JSch jsch = new JSch();
		if(port <=0){
			//连接服务器，采用默认端口
			session = jsch.getSession(user, ip);
		}else{
			//采用指定的端口连接服务器
			session = jsch.getSession(user, ip ,port);
		}
		//如果服务器连接不上，则抛出异常
		if (session == null) {
			throw new Exception("session is null");
		}
		//设置登陆主机的密码
		session.setPassword(psw);//设置密码   
		//设置第一次登陆的时候提示，可选值：(ask | yes | no)
		session.setConfig("StrictHostKeyChecking", "no");
		//设置登陆超时时间   
		session.connect(30000);
		try {
			//创建sftp通信通道
			channel = (Channel) session.openChannel("sftp");
			channel.connect(1000);
			ChannelSftp sftp = (ChannelSftp) channel;
			//从本地上传一个文件到服务器
			OutputStream outstream = sftp.put(dst);
			InputStream instream = new FileInputStream(src);
			byte b[] = new byte[1024];
			int n;
			while ((n = instream.read(b)) != -1) {
				outstream.write(b, 0, n);
			}
			outstream.flush();
			outstream.close();
			instream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.disconnect();
			channel.disconnect();
		}
	}
}
